<%#
 Copyright 2013-2020 the original author or authors from the JHipster project.

 This file is part of the JHipster project, see https://www.jhipster.tech/
 for more information.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-%>
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
<%_ if (enableTranslation) { _%>
import { JhiLanguageService } from 'ng-jhipster';
import { SessionStorageService } from 'ngx-webstorage';
<%_ } _%>
import { Observable, ReplaySubject, of } from 'rxjs';
import { shareReplay, tap, catchError } from 'rxjs/operators';
import { StateStorageService } from 'app/core/auth/state-storage.service';

import { SERVER_API_URL } from 'app/app.constants';
import { Account } from 'app/core/user/account.model';
<%_ if (websocket === 'spring-websocket') { _%>
import { TrackerService } from '../tracker/tracker.service';
<%_ } _%>

@Injectable({ providedIn: 'root' })
export class AccountService {
    private userIdentity: Account | null = null;
    private authenticationState = new ReplaySubject<Account | null>(1);
    private accountCache$?: Observable<Account | null>;

    constructor(
        <%_ if (enableTranslation) { _%>
        private languageService: JhiLanguageService,
        private sessionStorage: SessionStorageService,
        <%_ } _%>
        private http: HttpClient,
        <%_ if (websocket === 'spring-websocket') { _%>
        private trackerService: TrackerService,
        <%_ } _%>
        private stateStorageService: StateStorageService,
        private router: Router
    ) {}

    <%_ if (!skipUserManagement) { _%>
    save(account: Account): Observable<{}> {
        return this.http.post(SERVER_API_URL + '<%- apiUaaPath %>api/account', account);
    }
    <%_ } _%>

    authenticate(identity: Account | null): void {
        this.userIdentity = identity;
        this.authenticationState.next(this.userIdentity);
        <%_ if (websocket === 'spring-websocket') { _%>
        if (identity) {
            this.trackerService.connect();
        } else {
            this.trackerService.disconnect();
        }
        <%_ } _%>
    }

    hasAnyAuthority(authorities: string[] | string): boolean {
        if (!this.userIdentity || !this.userIdentity.authorities) {
            return false;
        }
        if (!Array.isArray(authorities)) {
            authorities = [authorities];
        }
        return this.userIdentity.authorities.some((authority: string) => authorities.includes(authority));
    }

    identity(force?: boolean): Observable<Account | null> {
        if (!this.accountCache$ || force || !this.isAuthenticated()) {
            this.accountCache$ = this.fetch().pipe(
                catchError(() => {
                    return of(null);
                }),
                tap((account: Account | null) => {
                    this.authenticate(account);

                    <%_ if (enableTranslation) { _%>
                    // After retrieve the account info, the language will be changed to
                    // the user's preferred language configured in the account setting
                    if (account && account.langKey) {
                        const langKey = this.sessionStorage.retrieve('locale') || account.langKey;
                        this.languageService.changeLanguage(langKey);
                    }
                    <%_ } _%>

                    if (account) {
                        this.navigateToStoredUrl();
                    }
                }),
                shareReplay()
            );
        }
        return this.accountCache$;
    }

    isAuthenticated(): boolean {
        return this.userIdentity !== null;
    }

    getAuthenticationState(): Observable<Account | null> {
        return this.authenticationState.asObservable();
    }

    getImageUrl(): string {
        return this.userIdentity ? this.userIdentity.imageUrl : '';
    }

    private fetch(): Observable<Account> {
        return this.http.get<Account>(SERVER_API_URL + '<%- apiUaaPath %>api/account');
    }

    private navigateToStoredUrl(): void {
        // previousState can be set in the authExpiredInterceptor and in the userRouteAccessService
        // if login is successful, go to stored previousState and clear previousState
        const previousUrl = this.stateStorageService.getUrl();
        if (previousUrl) {
            this.stateStorageService.clearUrl();
            this.router.navigateByUrl(previousUrl);
        }
    }
}
